package com.rem.concurrency.juc.my10ForkJoin;

import lombok.Data;

import java.util.concurrent.RecursiveTask;

/**
 * 并行执行任务！提高效率。大数据量！
 * 大数据：Map Reduce （把大任务拆分为小任务）
 * ForkJoin 特点：工作窃取
 *
 * @author Rem
 * @date 2021-03-10
 */

@Data
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if ((end - start) > temp) {
            //递归
            // 中间值
            long middle = (start + end) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            // 拆分任务，把任务压入线程队列
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
            // 拆分任务，把任务压入线程队列测试：
            task2.fork();
            return task1.join() + task2.join();

        } else {
            //自己运算
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }
    }

}
